package com.freight.message.utils;

import com.alibaba.fastjson.JSONObject;
import com.freight.common.core.constant.Constants;
import com.freight.common.core.exception.ServiceException;
import com.freight.common.core.utils.HttpUtils;
import com.freight.common.core.utils.StringUtils;
import com.freight.common.redis.service.RedisService;
import com.freight.tws.api.RemoteConfigClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 企业微信通知
 */
@Component
public class WeChatService {

    @Autowired
    private RemoteConfigClient remoteConfigClient;

    @Autowired
    RedisService redisService;

    /**
     * 通过企业微信通知
     */
    public void sendWeChatMsg(String msg) {
        if(StringUtils.isNotBlank(msg)) {
            String qyapi = remoteConfigClient.selectConfigByKey("wechat.api");
            if(StringUtils.isEmpty(qyapi)) {
                throw new ServiceException("企业微信api未配置");
            }
            // 判断通知是否过于频繁
            String m = redisService.getCacheObject(Constants.WECHAT_MSG + msg);
            if(StringUtils.isEmpty(m)) {
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("msgtype", "text");
                    JSONObject jo = new JSONObject();
                    jo.put("content", msg);
                    jsonObject.put("text", jo);
                    HttpUtils.doPost(qyapi, jsonObject.toJSONString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                redisService.setCacheObject(Constants.WECHAT_MSG + msg, msg, Constants.WECHAT_MSG_TIME, TimeUnit.MINUTES);
            }
        }
    }

}
